using WpfClient.Core.Interfaces;
using WpfClient.Core.Models;
using WpfClient.Shared.Exceptions;

namespace WpfClient.Core.Services
{
    /// <summary>
    /// 用户服务实现
    /// </summary>
    public class UserService : IUserService
    {
        private readonly IRepository<User> _userRepository;

        public UserService(IRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        public async Task<User?> GetUserByIdAsync(int id)
        {
            return await _userRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<User>> GetAllUsersAsync()
        {
            return await _userRepository.GetAllAsync();
        }

        public async Task<User> CreateUserAsync(string name, string email)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new BusinessException("用户名不能为空");

            if (string.IsNullOrWhiteSpace(email))
                throw new BusinessException("邮箱不能为空");

            if (await IsEmailExistsAsync(email))
                throw new BusinessException("邮箱已存在");

            var user = new User
            {
                Name = name.Trim(),
                Email = email.Trim().ToLower(),
                IsActive = true
            };

            return await _userRepository.AddAsync(user);
        }

        public async Task<User> UpdateUserAsync(User user)
        {
            if (user == null)
                throw new ArgumentNullException(nameof(user));

            var existingUser = await _userRepository.GetByIdAsync(user.Id);
            if (existingUser == null)
                throw new BusinessException("用户不存在");

            return await _userRepository.UpdateAsync(user);
        }

        public async Task DeleteUserAsync(int id)
        {
            var user = await _userRepository.GetByIdAsync(id);
            if (user == null)
                throw new BusinessException("用户不存在");

            await _userRepository.DeleteAsync(id);
        }

        public async Task<bool> IsEmailExistsAsync(string email)
        {
            var users = await _userRepository.GetAllAsync();
            return users.Any(u => u.Email.Equals(email.Trim(), StringComparison.OrdinalIgnoreCase));
        }
    }
}